from flask import Blueprint, request,g,make_response
import re,json
from arrow import arrow
from models.model import *
from db_init import db
from toolsa.cache import redis_cli
import datetime,time
import holidays
from datetime import datetime
users = Blueprint('/user', __name__, url_prefix="/user")


# 注册
@users.route("/reg", methods=["POST"])
def user_register():
    name = request.json.get('user')
    password = request.json.get('pwd')
    phone = request.json.get('phone')
    if not all([name, password, phone]):
        return {'msg': "字段不完整", 'code': 400}
    if not re.match(r"^1[3-9]\d{9}$", phone):
        return {'msg': "手机号不符合格式", 'code': 400}
    if User.query.filter_by(name=name).all():
        return {'msg': '用户名已存在', 'code': 400}
    try:
        user_lst = User(name=name, phone=phone, pwd=password)
        db.session.add(user_lst)
        db.session.commit()
        return "注册成功"
    except Exception as e:
        return f'注册出错,{e}'


# 登录
@users.route("/log", methods=["POST"])
def user_login():
    name = request.form.get('user')
    password = request.form.get('pwd')
    if not all([name, password]):
        return {'msg': "字段不完整", 'code': 400}
    if not User.query.filter_by(name=name).first():
        return {'msg': '用户名不存在', 'code': 400}
    user = User.query.filter_by(name=name).first()
    if user.pwd != password:
        return "密码错误"
#通过用户找对应的角色
    powers= sum([role.power for role in user.role_id],[])
    return {'name':user.name,'powers':{item.get('id'):item for item in item2dict(powers)}}


# 类别
@users.route('/cate', methods=['GET'])
def user_cate():
    cate = Cate.query.all()
    cate_lst = [{
        'id': i.id,
        'name': i.name
    } for i in cate]
    return {'msg': 'ok', 'data': cate_lst}


# 商品
@users.route('/goods', methods=["GET"])
def user_good():
    festival = list(holidays.China(years=2023))
    cate_id = request.args.get('id')
    user_name = request.args.get("name")
    uname = User.query.filter_by(name=user_name).first()
    login_time = uname.login_time
    log_date = time.mktime(login_time.timetuple())
    dates = datetime.fromtimestamp(log_date).date()
    goods = Goods.query.filter_by(cate_id=cate_id).all()
    if dates in festival:
        good_data = Goods.query.all()
        for i in good_data:
            if 0 < i.num < 2:
                discount1 = i.price * 0.8
                i.price_dis = discount1
                db.session.commit()
            elif i.num >= 2:
                discount2 = i.price + i.price * 0.5
                i.price_dis = discount2
                db.session.commit()
        goods_lst = [{
            'id': i.id,
            'name': i.name,
            'price': i.price_dis,
            'num': i.num,
            'img': i.img,
            'content': i.content,
        } for i in goods]
        return {'msg': 'ok', 'data': goods_lst}
    else:
        goods_lst = [{
            'id': i.id,
            'name': i.name,
            'price': i.price,
            'num': i.num,
            'img': i.img,
            'content': i.content,
        } for i in goods]
        return {'msg': '原价', 'data': goods_lst}


# 获取小料
@users.route('/small', methods=["GET"])
def user_small():
    name = request.args.get('name')
    goods = Goods.query.filter_by(name=name).first()
    small = goods.small
    small_lst = [{
        'id': i.id,
        'name': i.name
    } for i in small]
    return small_lst


# 商家
@users.route('/shangjia', methods=['GET'])
def user_business():
    business = Business.query.all()
    business_lst = [{
        'id': i.id,
        'name': i.name,
        'addr': i.addr,
        'open': i.open,
        'tel': i.tel
    } for i in business]
    return {'msg': 'ok', 'data': business_lst}


# 购物车
@users.route('/shop', methods=['POST'])
def shop_good():
    # 数据的操作
    uid = request.args.get("uid")
    g['uid'] = uid
    good_data = dict(request.json)
    good_data["user_id"] = uid
    good_id = good_data.pop('good_id')

    # 购物车
    shop = Shop(**good_data)
    db.session.add(shop)
    db.session.flush()

    # 成品
    db.session.add(Finish(good_id=good_id, shop_id=shop.id))

    # 整体提交
    db.session.commit()

    return {'msg': 'ok'}


@users.route('/order', methods=['POST'])
def shop2ood():
    # 数据的操作
    uid = request.args.get("uid")

    shops = Shop.query.filter_by(user_id=uid).all()

    order = Order()
    order.finish.extend([i.finish[0] for i in shops])

    # 整体提交
    db.session.add(order)
    db.session.commit()

    # 清空 购物车

    return {'msg': 'ok'}

# 签到
@users.route('/check', methods=['get'])
def check_in():
    uid = request.args.get('uid')
    check_data = Sign.query.filter_by(user_id=uid).first()
    todate = datetime.date.today()

    if not check_data:
        db.session.add(Sign(user_id=uid, status=True, check_date=datetime.date.today()))
    elif check_data.check_date and check_data.check_date >= todate:
        return "今天已签到"
    else:
        check_data.check_date = todate
    db.session.commit()
    return request_data(data={}, code=200)


@users.route('/check', methods=['put'])
def check_reset():
    Sign.query.update({"status": False})
    db.session.commit()
    return request_data(data={}, code=200)



# 获取
@users.route('/gshop_car', methods=[ 'GET'])
def get_shop():
        u_id = request.args.get('id')
        uid = User.query.filter_by(id=u_id).first().id
        shops = Shop.query.filter_by(user_id=uid).all()
        shop_lst = [{
            'id': i.id,
            'name': i.name,
            'price': i.price,
            'num': i.num
        } for i in shops]
        return shop_lst


# 成品
@users.route('/finish', methods=['POST', "GET"])
def user_finish():
    if request.method == 'POST':
        gid = request.args.get('gid')
        g_id = Goods.query.filter_by(id=gid).first().id
        oid = request.args.get('oid')
        o_id = Goods.query.filter_by(id=oid).first().id
        finish_lst = Finish(good_id=g_id, order_id=o_id)
        db.session.add(finish_lst)
        db.session.commit()
        return '添加成功'

# 订单
@users.route('/order', methods=['POST'])
def user_order():
    if request.method == "POST":
        addr = request.form.get('addr')
        state = int(request.form.get('state'))
        oid = request.form.get('oid')
        total = request.form.get('total')
        num = request.form.get('num')
        remark = request.form.get('remark')
        if not all([addr, state, oid, total, num, remark]):
            return {'msg': "字段不完整", 'code': 400}
        order_lst = Order(addr=addr, state=state, oid=oid, total=total, num=num, remark=remark)
        db.session.add(order_lst)
        db.session.commit()
        return '订单生成成功'
    else:
        order_id = request.args.get('id')
        orders = Order.query.filter_by(id=order_id).first()
        order_lst = [{
            'id': orders.id,
            'addr': orders.addr,
            'state': orders.state,
            'total': orders.total,
            'num': orders.num,
            'remark': orders.remark
        }]
        return order_lst


@users.route('/get_order', methods=["GET"])
def user_get():
        order_id = request.args.get('id')
        orders = Order.query.filter_by(id=order_id).first()
        order_lst = [{
            'id': orders.id,
            'addr': orders.addr,
            'state': orders.state,
            'total': orders.total,
            'num': orders.num,
            'remark': orders.remark
        }]
        return order_lst

@users.route('/redis_shop', methods=['GET'])
def get_redis_shop():
    uid = request.args.get('uid')
    data = redis_cli.hgetall(name=f'shop_{uid}')

    return {k: json.loads(v) for k, v in data.items()}

@users.route('/redis_shop', methods=['POST'])
def add_redis_shop():
    uid = request.args.get('uid')
    good_data = dict(request.json)
    redis_cli.hset(name=f'shop_{uid}', key=arrow.get().int_timestamp, value=json.dumps(good_data))
    return {'msg': 'ok'}


@users.route('/redis_shop', methods=['DELETE'])
def del_redis_shop():
    uid = request.args.get('uid')
    key = request.args.get('key')
    redis_cli.hdel(f'shop_{uid}', key)
    return {'msg': 'ok'}